﻿using System;
using System.Windows.Forms;
using SdmxMl.Manager;
using SdmxMl.Structure;

namespace SakeVar
{
    /// <summary>
    /// Dialog used to display codes and quality codes associsated to a variable.
    /// </summary>
    public partial class DlgCodeAndQuality :  Telerik.WinControls.UI.RadForm
    {
        #region Internal Members

        private CodeListType cltCodes;
        private CodeListType cltQuality;

        #endregion

        #region Constructor

        public DlgCodeAndQuality()
        {
            InitializeComponent();
        }
        #endregion

        #region Grid filling

        public void Update(CodeListType codes, CodeListType quality)
        {
            cltCodes = codes;
            cltQuality = quality;

            radButtonNavCodes.Enabled = cltCodes != null;
            radButtonNavQuality.Enabled = cltQuality != null;

            using (radGridView.DeferRefresh())
            {

                if (cltCodes != null)
                {
                    radTextBoxCodeList.Text = cltCodes.Name.ToString();
                    foreach (CodeType c in cltCodes.CodeList)
                        radGridView.MasterTemplate.Rows.Add(c.Id, c.Name.ToString());
                }
                if (cltQuality != null)
                {
                    radTextBoxQualityList.Text = cltQuality.Name.ToString();
                    foreach (CodeType c in cltQuality.CodeList)
                        radGridView.MasterTemplate.Rows.Add(c.Id, c.Name.ToString());
                }
            }
            radGridView.MasterTemplate.EnableGrouping = false;
        }
        #endregion

        #region Navigation to Codelist

        private void radButtonNavCodes_Click(object sender, EventArgs e)
        {
            NavigateToCodelist(cltCodes);
        }

        private void radButtonNavQuality_Click(object sender, EventArgs e)
        {
            NavigateToCodelist(cltQuality);

        }

        private void NavigateToCodelist(CodeListType clt)
        {
            try
            {
                if (clt != null)
                {
                    if (NavigationManager.LocatenavigateProject(clt.ArType, clt.FullIdent, null) == null)
                        NavigationManager.NavigateWithRegistry(clt.ArType, clt.FullIdent, true, null);
                    if (ReferenceManager.TreeSdmx.SelectedNode.Tag is CodeListType)
                        ReferenceManager.TreeSdmx.SelectedNode.ExpandAll();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

    }
}
